package app;

import com.alibaba.fastjson.JSON;
import domain.Access;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.api.java.tuple.Tuple4;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import udf.GaodeLocationMapFunction;
import udf.MySqlSinkT3;
import udf.MySqlSinkT4;

/**
 * Create by zhh on 2022/9/9.
 * 按照省份和渠道维度进行新老用户的统计分析
 */
public class ChannelAndProvinceUserAppV1 {
    public static void main(String[] args) throws Exception{
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        SingleOutputStreamOperator<Access> cleanData = env.readTextFile("data/access.json")
                .map(new MapFunction<String, Access>() {
            @Override
            public Access map(String s) throws Exception {
                //TODO... json==>Access
                try {
                    return JSON.parseObject(s, Access.class);//解析json文件
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }
        })
                .filter(x -> x != null)//过滤空
                .filter(new FilterFunction<Access>() {
                    @Override
                    //过滤启动的用户
                    public boolean filter(Access access) throws Exception {
                        return "startup".equals(access.event);
                    }
                })
                .map(new GaodeLocationMapFunction()).setParallelism(1);//使用自定义MapFunction获取从高德获取的IP定位信息


        SingleOutputStreamOperator<Tuple4<String, String, Integer, Integer>> result = cleanData.map(new MapFunction<Access, Tuple4<String, String, Integer, Integer>>() {
            @Override
            public Tuple4<String, String, Integer, Integer> map(Access access) throws Exception {
                return Tuple4.of(access.province, access.channel, access.nu, 1);//(省份，渠道，用户类型，1)
            }
        }).keyBy(new KeySelector<Tuple4<String, String, Integer, Integer>, Tuple3<String, String, Integer>>() {
            @Override
            public Tuple3<String, String, Integer> getKey(Tuple4<String, String, Integer, Integer> value) throws Exception {
                return Tuple3.of(value.f0, value.f1, value.f2);
            }
        }).sum(3);

        result.print("省份维度统计新老用户").setParallelism(1);
        result.addSink(new MySqlSinkT4());//自定义Sink，但要在utils包中的MySqlTableUtils中修改要Sink的表名和列名
        env.execute();
    }

}



